<!doctype html>
<html class="theme-next use-motion theme-next-mist">
<head>
  
<meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>

<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />

  <meta name="google-site-verification" content="K8DCBviaoTBKVs28YBB7IBIbospQ9RVlgSh81RYMUhY" />


  <meta name="baidu-site-verification" content="tXr3ZTm3Hx" />



  <link rel="stylesheet" type="text/css" href="/vendors/fancybox/source/jquery.fancybox.css?v=2.1.5"/>


<link rel="stylesheet" type="text/css" href="/css/main.css?v=0.4.5.1"/>

  <meta name="description" content="xgfe's blog. 鲜果前端的技术博客，鲜果前端研发部官方博客。前端基础技术研究：html, html5, javascript, css, css3；前端框架研究：angularJs, react, react native." />


  <meta name="keywords" content="android,源码,listview," />


  <link rel="alternate" target="_blank" href="/atom.xml" title="xgfe" type="application/atom+xml" />


  <link rel="shorticon icon" type="image/x-icon" href="http://p0.meituan.net/xgfe/2db359f56ce13be30dedef160e0e57ce16958.ico?v=0.4.5.1" />

<meta name="description" content="本文主要是分析ListView源码，重点关注复用机制。">
<meta name="keywords" content="android,源码,listview">
<meta property="og:type" content="article">
<meta property="og:title" content="ListView源码分析">
<meta property="og:url" content="http://xgfe.github.io/2018/02/09/caominkang/ListView源码分析/index.html">
<meta property="og:site_name" content="xgfe">
<meta property="og:description" content="本文主要是分析ListView源码，重点关注复用机制。">
<meta property="og:updated_time" content="2018-03-20T03:07:52.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="ListView源码分析">
<meta name="twitter:description" content="本文主要是分析ListView源码，重点关注复用机制。">


<script type="text/javascript" id="hexo.configuration">
  var CONFIG = {
    scheme: 'Mist',
    sidebar: 'post'
  };
</script>

  <title> ListView源码分析 | xgfe </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">
  <div style="position: fixed; top: -9999px; left: -9999px;">
    <img src="http://p0.meituan.net/xgfe/082a9624ba5ae8602150a2d43968463e49348.png" alt="xgfe"/>
  </div>
  <!--[if lte IE 8]>
  <div style=' clear: both; height: 59px; padding:0 0 0 15px; position: relative;margin:0 auto;'>
    <a href="http://windows.microsoft.com/en-US/internet-explorer/products/ie/home?ocid=ie6_countdown_bannercode">
      <img src="http://7u2nvr.com1.z0.glb.clouddn.com/picouterie.jpg" border="0" height="42" width="820"
           alt="You are using an outdated browser. For a faster, safer browsing experience, upgrade for free today or use other browser ,like chrome firefox safari."
           style='margin-left:auto;margin-right:auto;display: block;'/>
    </a>
  </div>
<![endif]-->
  

  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "//hm.baidu.com/hm.js?3601d4483819a5ab6ddabb0b6422a328";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>



  <div class="container one-column page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><h1 class="site-meta">
  <span class="logo-line-before"><i></i></span>
  <a href="/" class="brand" rel="start">
      <span class="logo">
        <i class="icon-next-logo"></i>
      </span>
      <span class="site-title">xgfe</span>
  </a>
  <span class="logo-line-after"><i></i></span>
</h1>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  
  

  
    <ul id="menu" class="menu menu-left">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            <i class="menu-item-icon icon-next-home"></i> <br />
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            <i class="menu-item-icon icon-next-archives"></i> <br />
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            <i class="menu-item-icon icon-next-tags"></i> <br />
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-join">
          <a href="/join" rel="section">
            <i class="menu-item-icon icon-next-join"></i> <br />
            加入我们
          </a>
        </li>
      
      <!-- slide-links added by felix -->
      <li class="menu-item menu-item-slides" style="opacity: 1; transform: translateY(0px);">
        <a href="http://xgfe.github.io/Basics/" target="_blank" rel="section">
          <i class="menu-item-icon icon-next-slides"></i> <br>
          Basics
        </a>
      </li>
      <li class="menu-item menu-item-slides" style="opacity: 1; transform: translateY(0px);">
        <a href="https://slides.com/xgfe" target="_blank" rel="section">
          <i class="menu-item-icon icon-next-slides"></i> <br>
          Slides
        </a>
      </li>

      
      
    </ul>
  

  
    <div class="site-search">
      

    </div>
  

    <div class="site-search">
      <form class="site-search-form" id="gg-form" action="https://www.google.com/webhp" >
        <input type="text" name="q" id="gg-search-input" class="menu-search-input">
      </form>
    </div>
</nav>
 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div id="content" class="content"> 

  <div id="posts" class="posts-expand">
    

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <header class="post-header">

      
      
        <h1 class="post-title" itemprop="name headline">
          
          
            
              ListView源码分析
            
          
        </h1>
      

      <div class="post-meta">
        <span class="post-time">
          发表于
          <time itemprop="dateCreated" datetime="2018-02-09T13:12:00+08:00" content="2018-02-09">
            2018-02-09
          </time>
        </span>

        
          <span class="post-category" >
            &nbsp; | &nbsp; 作者
            
              <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
                <a href="/categories/caominkang/" itemprop="url" rel="index">
                  <span itemprop="name">caominkang</span>
                </a>
              </span>

              
              

            
          </span>
        

        
          
        

        <!-- tags 挪动位置 -->
        
          <span class="post-tags">
            &nbsp; | &nbsp;
            
              <a href="/tags/android/" rel="tag"><i class="icon-next-tags"></i>android</a>
            
              <a href="/tags/源码/" rel="tag"><i class="icon-next-tags"></i>源码</a>
            
              <a href="/tags/listview/" rel="tag"><i class="icon-next-tags"></i>listview</a>
            
          </span>
        
      </div>
    </header>

    <div class="post-body">

      
      

      
        <span itemprop="articleBody"><p>本文主要是分析ListView源码，重点关注复用机制。</p>
<a id="more"></a>
<h1 id="ListView源码解析"><a href="#ListView源码解析" class="headerlink" title="ListView源码解析"></a>ListView源码解析</h1><p>&nbsp;&nbsp;本文分为三个部分，第一个部分提取出RecycleBin的相关代码，对RecyleBin做基本讲解；第二部分讲解ListView初始化时onLayout过程；第三部分讲解ListView如何在屏幕滑动中实现复用。</p>
<h2 id="一、RecycleBin"><a href="#一、RecycleBin" class="headerlink" title="一、RecycleBin"></a>一、RecycleBin</h2><p>&nbsp;&nbsp;RecycleBin是AbsListView的子类，也就是说只要是继承自AbsListView的，都可以使用这个机制，代码结构大概如下：</p>
<pre><code>class RecycleBin{
    private int mFirstPosition;
    private View[] mActiveViews = new View[0];
    private int mViewTypeCount;
    private ArrayList&lt;View&gt;[] mScrapViews;
    private ArrayList&lt;View&gt; mCurrentScrap;
    void fillActiveViews(int childCount,int firstActivePostion)
    void getActiveView(int position);
    void addScrapView(View scrap);
    View getSrapView(int position);
    public void setViewTypeCount(int viewTypeCount);
}
</code></pre><p>下面介绍字段和api：</p>
<ul>
<li>mFirstPosition指的是mActiveView[0]中存储的View在数据中的position。</li>
<li>mActiveViews缓存的是第一屏的数据，后面的讲解中会说明，主要是在ListView初始化中起作用</li>
<li>mViewTypeCount代表数据种类，值由setViewTypeCount方法设置。ListView可以处理不同种类的数据</li>
<li>mScrapViews用来缓存移出到屏幕外的view，因为ListView支持不同种类数据，所以mScrapViews是一个二维数组，对应不同种类数据，使用不同的ArrayList去缓存。</li>
<li>fillActiveViews是将屏幕上可以看到的view缓存到mActiveViews中</li>
<li>getActiveViews将指定的位置的view从mActiveViews中取出来，需要注意的是，取出后再次获取该位置view会返回空。</li>
<li>getScrapView用于从mScrapView中取出view，由于同种数据类型的view都是相同的，所以该方法只是返回该类型最后一个位置的view。</li>
</ul>
<p>也就是说RecycleBin有两种缓存view的模式：ActiveView和ScrapView.ListView在初始化过程中使用mActiveViews来缓存显示在屏幕中的view，在滚动过程中使用mScrapView缓存移除到屏幕外的数据，实现复用。下面我来具体看ListView是如何通过调用RecycleBin的方法来管理view的复用。</p>
<h2 id="二、ListView初始化过程"><a href="#二、ListView初始化过程" class="headerlink" title="二、ListView初始化过程"></a>二、ListView初始化过程</h2><p>&nbsp;&nbsp;重点关注ListView初始化过程中onLayout过程，因为与RecycleBin交互主要在这个过程。我们知道，android视图树的根节点是FrameLayout子类，而FrameLayout会让子view执行两次onLayout过程，ListView也不例外，也会有两次onLayout过程。</p>
<h3 id="1-第一次onLayout"><a href="#1-第一次onLayout" class="headerlink" title="1.第一次onLayout"></a>1.第一次onLayout</h3><p>&nbsp;&nbsp;ListView中没有复写父类AbsListView的onLayout方法，不过在父类onLayout中，做完数据判断后，直接调用了layoutChildren，并且注释有说明，子类不应该复写onLayout方法，而该复写layoutChildren。由于layoutChildren需要针对两次onLayout处理，所以判断和分支流程特别复杂，抽取出第一次调用的流程，大概如下：</p>
<pre><code> protected void layoutChildren(){
    int childCount = getChildCount();

    switch(mLayoutMode){

    }
    boolean dataChanged = mDataChanged;
    if(dataChanged){

    }else{
        recycleBin.fillActiveView(childCount,firstPosition);
    }
    detachAllViewsFromParent();
    switch (mLayoutMode){
        default:
            if(childCount==0)
                fillFromTop(childrenTop);
            else
                fillSpecific(0,childrenTop)

    }

}
</code></pre><p>&nbsp;&nbsp;以上是代码结构，省去了很多与分析流程无关的代码，可以看到，由于我们数据源没有变化，dataChanged等于false，进入fillActiveViews，但是此时ListView没有任何子view，childCount为0，这行代码没有任何作用，进入switch语句后，进入default分支，调用fillFromTop。我们进入该函数，发现主要调用了fillDown方法，完整代码如下</p>
<pre><code>private View fillDown(int pos, int nextTop) {
    View selectedView = null;
    int end = (getBottom() - getTop()) - mListPadding.bottom;
    while (nextTop &lt; end &amp;&amp; pos &lt; mItemCount) {
        // is this the selected item?  
        boolean selected = pos == mSelectedPosition;
        View child = makeAndAddView(pos, nextTop, true, mListPadding.left, selected);
        nextTop = child.getBottom() + mDividerHeight;
        if (selected) {
            selectedView = child;
        }
        pos++;
    }
    return selectedView;
}
</code></pre><p>&nbsp;&nbsp;可以看到，循环调用makeAndAddView（）方法，终止条件是数据项加载完或者最后一个子view的top小于ListView的底部。实现从ListView顶部一直填充到ListView底部，那么makeAndAddView方法肯定是构建view并且填充view到ListView中，下面是相关代码：</p>
<pre><code> private View makeAndAddView(int position, int y, boolean flow, int childrenLeft,
                            boolean selected) {
    View child;
    if (!mDataChanged) {
        // Try to use an exsiting view for this position
        child = mRecycler.getActiveView(position);
        if (child != null) {
            // Found it -- we&apos;re using an existing child
            // This just needs to be positioned
            setupChild(child, position, y, flow, childrenLeft, selected, true);
            return child;
        }
    }
    // Make a new view for this position, or convert an unused view if possible
    child = obtainView(position, mIsScrap);
    // This needs to be positioned and measured
    setupChild(child, position, y, flow, childrenLeft, selected, mIsScrap[0]);
    return child;
}
</code></pre><p>&nbsp;&nbsp;首先尝试通过recycler的getActiveView获取view，由于没有缓存过任何view，这里是获取不到的，再使用obtainView获取view。代码如下</p>
<pre><code>View obtainView(int position, boolean[] isScrap) {
    isScrap[0] = false;
    View scrapView;
    scrapView = mRecycler.getScrapView(position);
    View child;
    if (scrapView != null) {
        child = mAdapter.getView(position, scrapView, this);
        if (child != scrapView) {
            mRecycler.addScrapView(scrapView);
            if (mCacheColorHint != 0) {
                child.setDrawingCacheBackgroundColor(mCacheColorHint);
            }
        } else {
            isScrap[0] = true;
            dispatchFinishTemporaryDetach(child);
        }
    } else {
        child = mAdapter.getView(position, null, this);
        if (mCacheColorHint != 0) {
            child.setDrawingCacheBackgroundColor(mCacheColorHint);
        }
    }
    return child;
}
</code></pre><p>&nbsp;&nbsp;首先尝试从recyclerBin中获取scrapView，获取成功后作为参数传入Adapter.getView方法中，若获取失败，则将null传入Adapter.getView方法中。我们知道，在使用ListView时需要自定义Adapter，会复写getView方法，通常如下：</p>
<pre><code> public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
    Fruit fruit = getItem(position);
    View view;
    ViewHolder viewHolder;
    if (convertView == null) {
        view = LayoutInflater.from(getContext()).inflate(resourceId, parent, false);
        viewHolder = new ViewHolder();
        viewHolder.fruitImage = view.findViewById(R.id.fruit_image);
        viewHolder.fruitName = view.findViewById(R.id.fruit_name);
        view.setTag(viewHolder);

    } else {
        view = convertView;
        viewHolder = (ViewHolder) view.getTag();
    }
    viewHolder.fruitImage.setImageResource(fruit.getImageId());
    viewHolder.fruitName.setText(fruit.getName());
    if(position==0)
        view.setBackgroundColor(Color.RED);

    return view;

}
</code></pre><p>&nbsp;&nbsp;我们可以看到，convertView为空时会使用LayoutInflater加载布局，如果不为空的话，直接复用convertView。到这里obtainView逻辑已经清楚了，回到makeAndAddView中，会将obtainView得到的view传入到setUpChild方法中，然后会调用addViewInLayout将该view添加到ListView中。也就是说第一次onLayout 方法使用Inflater加载了刚好一屏幕数据，其他数据并没有加载。</p>
<p>###2.第二次onLayout<br>&nbsp;&nbsp;我们依然从layoutChild方法开始，代码结构如下：</p>
<pre><code>protected void layoutChildren(){
    int childCount = getChildCount();

    switch(mLayoutMode){

    }
    boolean dataChanged = mDataChanged;
    if(dataChanged){

    }else{
        recycleBin.fillActiveView(childCount,firstPosition);
    }
    detachAllViewsFromParent();
    switch (mLayoutMode){
        default:
            if(childCount==0)
                fillFromTop(childrenTop);
            else
                fillSpecific(0,childrenTop)

    }

}
</code></pre><p>&nbsp;&nbsp;这次我们可以看到由于childCount已经不是0，代码流程如下：</p>
<ul>
<li>recycleBin.fillActiveView():将屏幕中的view缓存到ActiveView[]中</li>
<li>detachAllViewsFromParent():将第一次onLayout加入到ListView中的所有view从ListView中detach</li>
<li>fillSpecific（0，childrenTop）将view加载到ListView中</li>
</ul>
<p>&nbsp;&nbsp;fillSpecific是第一次onLayout过程中没有用到的方法，这个方法逻辑和fillDown很相似，不过是先加载指定位置view再分别加载两边view，由于传入的position是0，效果上基本和fillDown一样。所有我们还是关注makeAndAddView:</p>
<pre><code> private View makeAndAddView(int position, int y, boolean flow, int childrenLeft,
                            boolean selected) {
    View child;
    if (!mDataChanged) {
        // Try to use an exsiting view for this position
        child = mRecycler.getActiveView(position);
        if (child != null) {
            // Found it -- we&apos;re using an existing child
            // This just needs to be positioned
            setupChild(child, position, y, flow, childrenLeft, selected, true);
            return child;
        }
    }
    // Make a new view for this position, or convert an unused view if possible
    child = obtainView(position, mIsScrap);
    // This needs to be positioned and measured
    setupChild(child, position, y, flow, childrenLeft, selected, mIsScrap[0]);
    return child;
}
</code></pre><p>&nbsp;&nbsp;这次代码逻辑就很简单了，mRecycler.getActiveView从缓存中获取view后直接将view传入setUpChild中，不过与第一次调用该方法不同的是，最后一个参数传入的是true，标记该view是使用的缓存，根据该标记，setUpChild方法内会走到attachViewToParent,将该view attach到ListView中。两次onLayout总体来说是这样的：</p>
<ul>
<li>使用inflater加载第一屏数据</li>
<li>将第一屏数据加入到recycleBin的ActiveViews中，并将这些view从ListView中移除</li>
<li>将ActiveViews中的view取出，重新attach到ListView中</li>
</ul>
<p>&nbsp;&nbsp;也就是说，在onLayout阶段，ActiveView主要是缓存第一次加载的数据，以避免因为两次onLayout产生重复数据</p>
<h2 id="三、屏幕滑动"><a href="#三、屏幕滑动" class="headerlink" title="三、屏幕滑动"></a>三、屏幕滑动</h2><p>&nbsp;&nbsp;屏幕滑动的处理是写在AbsListView中，触摸监听函数是onTouchEvent（），该函数会针对不同类型的触摸事件进行处理，而在屏幕上滑动事件对应的是ACTION_MOVE,而该case又嵌套一个switch分支，针对TOUCH_MODE处理，我们直接看TOUCH_MODE_SRCOLL,对应手指在屏幕上滑动。在该case内，调用了trackMotionScroll方法，也就是说只要手指在屏幕上滑动，trackMotionScroll就会被调用，trackMotion中核心代码如下：</p>
<pre><code>final boolean down = incrementalDeltaY&lt;0;
 if(down)
{
    final int top = listPadding.top - incrementalDeltaY;
    for (int i = 0; i &lt; childCount; i++) {
        final View child = getChildAt(i);
        if (child.getBottom() &gt;= top) {
            break;
        } else {
            count++;
            int position = firstPosition + i;
            if (position &gt;= headerViewsCount &amp;&amp; position &lt; footerViewsStart) {
                mRecycler.addScrapView(child);
            }
        }
    }
} else
{
    final int bottom = getHeight() - listPadding.bottom - incrementalDeltaY;
    for (int i = childCount - 1; i &gt;= 0; i--) {
        final View child = getChildAt(i);
        if (child.getTop() &lt;= bottom) {
            break;
        } else {
            start = i;
            count++;
            int position = firstPosition + i;
            if (position &gt;= headerViewsCount &amp;&amp; position &lt; footerViewsStart) {
                mRecycler.addScrapView(child);
            }
        }
    }
}
</code></pre><p>&nbsp;&nbsp;incrementalDeltaY是上次触发event事件时手指在y方向的改变量，如果小于0说明在屏幕上下滑，进入down为true流程。从ListView第一个child开始判断，只要该view的bottom小于ListView的top，说明该view已经划出了屏幕，调用mRecycler.addScrapView将该view缓存到scrapViews中,用count记录下缓存的数量。这样滑出屏幕的view已经缓存下来了，继续看接下来代码:</p>
<pre><code>if (count &gt; 0) {
    detachViewsFromParent(start, count);
}
offsetChildrenTopAndBottom(incrementalDeltaY);  
if (down) {
    mFirstPosition += count;
}
invalidate();
final int absIncrementalDeltaY = Math.abs(incrementalDeltaY);  
if (spaceAbove &lt; absIncrementalDeltaY || spaceBelow &lt; absIncrementalDeltaY) {
    fillGap(down);
}
</code></pre><p>代码流程如下：</p>
<ul>
<li>调用detachViewFromParent，将滑出屏幕的view从ListView中detach掉</li>
<li>调用offsetChildrenTopAndBottom按照便宜量平移剩下的子view，实现滑动效果</li>
<li>调用fillGap处理将要滑动到屏幕内的view</li>
</ul>
<p>那我们看fillGap如何处理将要移入屏幕的子view的：</p>
<pre><code>void fillGap(boolean down) {
    final int count = getChildCount();
    if (down) {
        final int startOffset = count &gt; 0 ? getChildAt(count - 1).getBottom() + mDividerHeight :
                getListPaddingTop();
        fillDown(mFirstPosition + count, startOffset);
        correctTooHigh(getChildCount());
    } else {
        final int startOffset = count &gt; 0 ? getChildAt(0).getTop() - mDividerHeight :
                getHeight() - getListPaddingBottom();
        fillUp(mFirstPosition - 1, startOffset);
        correctTooLow(getChildCount());
    }
}
</code></pre><p>&nbsp;&nbsp;我们可以看到，方法内部主要是调用了fillDown或者fillUp，我们来回顾下fillDown的逻辑</p>
<ul>
<li>从activeView中获取缓存的view</li>
<li>若第一步获取不成功，则调用obtainView获取view</li>
<li>obtainView会先尝试复用scrapView中的view</li>
<li>若上一步复用失败，则使用inflater加载布局来生成view</li>
<li>将得到的view传入setUpChild中以加入ListView中</li>
</ul>
<p>&nbsp;&nbsp;也就是说，在滑动屏幕时，每当有view从屏幕中移出，就先缓存到scrapViews中，再从ListView中移除该view，而每当有view要滑入屏幕中时，会从scrapViews中取出缓存的view,将其中的数据更新为相应位置的数据，再加入到ListView中，这样的循环使得ListView无论加载多少数据，都是固定数量的view在循环利用，内存都不会增加。</p>
<h2 id="四、总结"><a href="#四、总结" class="headerlink" title="四、总结"></a>四、总结</h2><p>&nbsp;&nbsp;ListView通过activeView解决两次onLayout过程中数据重复问题，通过scrapView解决滑动过程中view复用问题。无论是onLayout过程还是滑动过程，都是采用attach-detach-attach的操作思路，将两个阶段统一为一个抽象操作，以实现代码的复用。</p>
</span>
      
    </div>

    <footer class="post-footer">

      
        <div class="post-nav">
          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/03/04/zhouyinian/React-component/" rel="prev">实现一个React 组件</a>
            
          </div>

          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/01/26/zhoushiqi/Less-VS-Sass/" rel="next">Less Vs Sass</a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
        <!-- JiaThis Button BEGIN -->
<div class="jiathis_style">
  <a class="jiathis_button_tsina"></a>
  <a class="jiathis_button_tqq"></a>
  <a class="jiathis_button_weixin"></a>
  <a class="jiathis_button_cqq"></a>
  <a class="jiathis_button_douban"></a>
  <a class="jiathis_button_renren"></a>
  <a class="jiathis_button_qzone"></a>
  <a class="jiathis_button_kaixin001"></a>
  <a class="jiathis_button_copy"></a>
  <a href="http://www.jiathis.com/share" class="jiathis jiathis_txt jiathis_separator jtico jtico_jiathis" target="_blank"></a>
  <a class="jiathis_counter_style"></a>
</div>
<script type="text/javascript" >
  var jiathis_config={
    hideMore:false
  }
</script>
<script type="text/javascript" src="http://v3.jiathis.com/code/jia.js" charset="utf-8"></script>
<!-- JiaThis Button END -->

      
    </div>
  </div>

 </div>

        

        
          <div class="comments" id="comments">
            <div id="SOHUCS" sid="" ></div>
          </div>
        
      </div>

      
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <a href="https://github.com/xgfe" target="_blank"><img class="site-author-image" src="http://p0.meituan.net/xgfe/082a9624ba5ae8602150a2d43968463e49348.png" alt="xgfe" itemprop="image"/></a>
          <p class="site-author-name" itemprop="name">xgfe</p>
        </div>
        <p class="site-description motion-element" itemprop="description">xgfe's blog. 鲜果前端的技术博客，鲜果前端研发部官方博客。前端基础技术研究：html, html5, javascript, css, css3；前端框架研究：angularJs, react, react native.</p>
        <nav class="site-state motion-element">
          <div class="site-state-item site-state-posts">
            <a href="/archives">
              <span class="site-state-item-count">89</span>
              <span class="site-state-item-name">日志</span>
            </a>
          </div>

          <div class="site-state-item site-state-categories">
            
              <span class="site-state-item-count">37</span>
              <span class="site-state-item-name">作者</span>
              
          </div>

          <div class="site-state-item site-state-tags">
            <a href="/tags">
              <span class="site-state-item-count">131</span>
              <span class="site-state-item-name">标签</span>
              </a>
          </div>

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" target="_blank" rel="alternate">
              <i class="menu-item-icon icon-next-feed"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/xgfe" target="_blank">GitHub</a>
              </span>
            
          
        </div>

        
        

        <div class="links-of-author motion-element">
          
        </div>

      </section>

      
        <section class="post-toc-wrap sidebar-panel-active">
          <div class="post-toc-indicator-top post-toc-indicator"></div>
          <div class="post-toc">
            
            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#ListView源码解析"><span class="nav-number">1.</span> <span class="nav-text">ListView源码解析</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#一、RecycleBin"><span class="nav-number">1.1.</span> <span class="nav-text">一、RecycleBin</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#二、ListView初始化过程"><span class="nav-number">1.2.</span> <span class="nav-text">二、ListView初始化过程</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-第一次onLayout"><span class="nav-number">1.2.1.</span> <span class="nav-text">1.第一次onLayout</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#三、屏幕滑动"><span class="nav-number">1.3.</span> <span class="nav-text">三、屏幕滑动</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#四、总结"><span class="nav-number">1.4.</span> <span class="nav-text">四、总结</span></a></li></ol></li></ol></div>
            
          </div>
          <div class="post-toc-indicator-bottom post-toc-indicator"></div>
        </section>
      

    </div>
  </aside>


    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner"> <div class="copyright" >
  
  &copy; &nbsp; 
  <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="icon-next-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">xgfe</span>
</div>

<div class="powered-by">
  由 <a class="theme-link" target="_blank" href="http://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Mist
  </a>
</div>


 </div>
    </footer>

    <div class="back-to-top"></div>
  </div>

  <script type="text/javascript" src="/vendors/jquery/index.js?v=2.1.3"></script>

  
  
  
    <script type="text/javascript"> 
(function(){ 
var appid = 'cysWiXvkm'; 
var conf = 'prod_fc970dbe85103c7a79b2c4f3dc7fb190'; 
var width = window.innerWidth || document.documentElement.clientWidth; 
if (width < 960) { 
window.document.write('<script id="changyan_mobile_js" charset="utf-8" type="text/javascript" src="http://changyan.sohu.com/upload/mobile/wap-js/changyan_mobile.js?client_id=' + appid + '&conf=' + conf + '"><\/script>'); } else { var loadJs=function(d,a){var c=document.getElementsByTagName("head")[0]||document.head||document.documentElement;var b=document.createElement("script");b.setAttribute("type","text/javascript");b.setAttribute("charset","UTF-8");b.setAttribute("src",d);if(typeof a==="function"){if(window.attachEvent){b.onreadystatechange=function(){var e=b.readyState;if(e==="loaded"||e==="complete"){b.onreadystatechange=null;a()}}}else{b.onload=a}}c.appendChild(b)};loadJs("http://changyan.sohu.com/upload/changyan.js",function(){window.changyan.api.config({appid:appid,conf:conf})}); } })(); </script>
    

  


  
  
  <script type="text/javascript" src="/vendors/fancybox/source/jquery.fancybox.pack.js"></script>
  <script type="text/javascript" src="/js/fancy-box.js?v=0.4.5.1"></script>


  <script type="text/javascript" src="/js/helpers.js?v=0.4.5.1"></script>
  

  <script type="text/javascript" src="/vendors/velocity/velocity.min.js"></script>
  <script type="text/javascript" src="/vendors/velocity/velocity.ui.min.js"></script>

  <script type="text/javascript" src="/js/motion_global.js?v=0.4.5.1" id="motion.global"></script>




  <script type="text/javascript" src="/js/nav-toggle.js?v=0.4.5.1"></script>
  <script type="text/javascript" src="/vendors/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  
<script type="text/javascript" src="/js/bootstrap.scrollspy.js?v=0.4.5.1" id="bootstrap.scrollspy.custom"></script>


<script type="text/javascript" id="sidebar.toc.highlight">
  $(document).ready(function () {
    var tocSelector = '.post-toc';
    var $tocSelector = $(tocSelector);
    var activeCurrentSelector = '.active-current';

    $tocSelector
      .on('activate.bs.scrollspy', function () {
        var $currentActiveElement = $(tocSelector + ' .active').last();

        removeCurrentActiveClass();
        $currentActiveElement.addClass('active-current');

        $tocSelector[0].scrollTop = $currentActiveElement.position().top;
      })
      .on('clear.bs.scrollspy', function () {
        removeCurrentActiveClass();
      });

    function removeCurrentActiveClass () {
      $(tocSelector + ' ' + activeCurrentSelector)
        .removeClass(activeCurrentSelector.substring(1));
    }

    function processTOC () {
      getTOCMaxHeight();
      toggleTOCOverflowIndicators();
    }

    function getTOCMaxHeight () {
      var height = $('.sidebar').height() -
                   $tocSelector.position().top -
                   $('.post-toc-indicator-bottom').height();

      $tocSelector.css('height', height);

      return height;
    }

    function toggleTOCOverflowIndicators () {
      tocOverflowIndicator(
        '.post-toc-indicator-top',
        $tocSelector.scrollTop() > 0 ? 'show' : 'hide'
      );

      tocOverflowIndicator(
        '.post-toc-indicator-bottom',
        $tocSelector.scrollTop() >= $tocSelector.find('ol').height() - $tocSelector.height() ? 'hide' : 'show'
      )
    }

    $(document).on('sidebar.motion.complete', function () {
      processTOC();
    });

    $('body').scrollspy({ target: tocSelector });
    $(window).on('resize', function () {
      if ( $('.sidebar').hasClass('sidebar-active') ) {
        processTOC();
      }
    });

    onScroll($tocSelector);

    function onScroll (element) {
      element.on('mousewheel DOMMouseScroll', function (event) {
          var oe = event.originalEvent;
          var delta = oe.wheelDelta || -oe.detail;

          this.scrollTop += ( delta < 0 ? 1 : -1 ) * 30;
          event.preventDefault();

          toggleTOCOverflowIndicators();
      });
    }

    function tocOverflowIndicator (indicator, action) {
      var $indicator = $(indicator);
      var opacity = action === 'show' ? 0.4 : 0;
      $indicator.velocity ?
        $indicator.velocity('stop').velocity({
          opacity: opacity
        }, { duration: 100 }) :
        $indicator.stop().animate({
          opacity: opacity
        }, 100);
    }

  });
</script>

<script type="text/javascript" id="sidebar.nav">
  $(document).ready(function () {
    var html = $('html');
    var TAB_ANIMATE_DURATION = 200;
    var hasVelocity = $.isFunction(html.velocity);

    $('.sidebar-nav li').on('click', function () {
      var item = $(this);
      var activeTabClassName = 'sidebar-nav-active';
      var activePanelClassName = 'sidebar-panel-active';
      if (item.hasClass(activeTabClassName)) {
        return;
      }

      var currentTarget = $('.' + activePanelClassName);
      var target = $('.' + item.data('target'));

      hasVelocity ?
        currentTarget.velocity('transition.slideUpOut', TAB_ANIMATE_DURATION, function () {
          target
            .velocity('stop')
            .velocity('transition.slideDownIn', TAB_ANIMATE_DURATION)
            .addClass(activePanelClassName);
        }) :
        currentTarget.animate({ opacity: 0 }, TAB_ANIMATE_DURATION, function () {
          currentTarget.hide();
          target
            .stop()
            .css({'opacity': 0, 'display': 'block'})
            .animate({ opacity: 1 }, TAB_ANIMATE_DURATION, function () {
              currentTarget.removeClass(activePanelClassName);
              target.addClass(activePanelClassName);
            });
        });

      item.siblings().removeClass(activeTabClassName);
      item.addClass(activeTabClassName);
    });

    $('.post-toc a').on('click', function (e) {
      e.preventDefault();
      var targetSelector = escapeSelector(this.getAttribute('href'));
      var offset = $(targetSelector).offset().top;
      hasVelocity ?
        html.velocity('stop').velocity('scroll', {
          offset: offset  + 'px',
          mobileHA: false
        }) :
        $('html, body').stop().animate({
          scrollTop: offset
        }, 500);
    });

    // Expand sidebar on post detail page by default, when post has a toc.
    var $tocContent = $('.post-toc-content');
    if (isDesktop() && CONFIG.sidebar === 'post') {
      if ($tocContent.length > 0 && $tocContent.html().trim().length > 0) {
        displaySidebar();
      }
    }
  });
</script>



  <script type="text/javascript">
    $(document).ready(function () {
      if (CONFIG.sidebar === 'always') {
        displaySidebar();
      }
      if (isMobile()) {
        FastClick.attach(document.body);
      }
    });
  </script>

  

  
  

  
  <script type="text/javascript" src="/js/lazyload.js"></script>
  <script type="text/javascript">
    $(function () {
      $("#posts").find('img').lazyload({
        placeholder: "/images/loading.gif",
        effect: "fadeIn"
      });
    });
  </script>

  <!-- google search, added by felix -->
  <script>
      $('#gg-form').on('submit', function(e) {
        var keyword = $.trim($(this).find('#gg-search-input').val());
        if (keyword) {
          location.href = 'https://www.google.com.hk/?gfe_rd=cr&ei=hXw8VpjtHuLC8AeSuIjQAg&gws_rd=ssl#safe=strict&q='+encodeURIComponent(keyword)+'+site:xgfe.github.io';
        }
        return false;
      });
  </script>
  <!-- baidu 站长自动推送 -->
  <script>
  (function(){
      var bp = document.createElement('script');
      bp.src = '//push.zhanzhang.baidu.com/push.js';
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(bp, s);
  })();
  </script>
</body>
</html>
